<template>
  <div>
    <!-- 步骤条 -->
    <div class="auth-step">
       <el-steps finish-status="success" :active="activeStep">
         <el-step title="基本信息" />
         <el-step title="农户认证" />
         <el-step title="提交审核" />
      </el-steps>
      </div>
     <!-- 第一步，基本信息 -->
     <div v-show="activeStep === 0" class="auth-form-section">
       <BaseInfoStep
         ref="baseInfoRef"
         :form="form"
         :rules="rules"
         :main-products-dict="mainProductsDict"
         :farmer-type-dict="farmerTypeDict"
       />
     </div>
     <!-- 第二步，农户证明 -->
     <div v-show="activeStep === 1" class="auth-form-section">
       <AuthInfoStep
         ref="authInfoRef"
         :form="form"
         :rules="rules"
         />
     </div>
     <!-- 第三步，确认信息 -->
     <div v-show="activeStep === 2" class="auth-form-section">
       <ConfirmInfoStep
         ref="confirmInfoRef"
         :form="form"
         :rules="rules"
         :farmer-type-dict="farmerTypeDict"
         :main-products-dict="mainProductsDict"
         />
     </div>
     <!-- 表单操作按钮 -->
     <div class="form-actions-button">
       <el-button type="primary" @click="handleFormActionsPrev" v-show="activeStep != 0">上一步</el-button>
       <el-button type="primary" @click="handleFormActionsNext" :loading="loading">
        {{ showText(activeStep,loading) }}
      </el-button>
     </div>
  </div>
 </template>
 
 <script setup>
 import { ElMessage } from 'element-plus';
 import AuthInfoStep from './steps/AuthInfoStep.vue';
 import BaseInfoStep from './steps/BaseInfoStep.vue';
 import ConfirmInfoStep from './steps/ConfirmInfoStep.vue';
 import { ref, getCurrentInstance } from 'vue';
 import { addFarmers, getAuthStatusInfo } from '@/api/assisting/farmers';
 
 // 获取当前组件实例
 const { proxy } = getCurrentInstance()
 // 当前步骤
const activeStep = ref(0)
 // 加载状态
const loading = ref(false)

 
 // 获取字典数据 - 确保键名与后端一致
 const dictResult = proxy.useDict('main_products', 'famer_type', 'auth_status')
 const mainProductsDict = ref(dictResult.main_products || [])
 const farmerTypeDict = ref(dictResult.famer_type || [])
 const authStatusDict = ref(dictResult.auth_status || [])
 
 // 表单数据
 const form = ref({
     farmerType: '1', // 农户类型 默认为第一个合作社
     realName: null, // 真实姓名/合作社名称
     idCard: null, // 身份证
     phone: null, // 联系电话
     address: null, // 地址
     mainProducts: [], //主要农产品
     scale: null, // 土地规模
     idCardFront: [], // 身份证正面
     idCardBack: [], // 身份证反面
     landProof: [], // 土地证明
     productPhotos: [], // 产品照片
     otherProof: [], // 其他证明 
 })
 
 // 表单验证规则
 const rules = ref({
     farmerType: [
       { required: true, message: "农户类型不能为空", trigger: "change" }
     ],
     realName: [
       { required: true, message: "真实姓名/合作社名称不能为空", trigger: "blur" }
     ],
     idCard: [
       { required: true, message: "身份证号不能为空", trigger: "blur" }
     ],
     phone: [
       { required: true, message: "电话号码不能为空", trigger: "blur" }
     ],
     address: [
       { required: true, message: "详细地址不能为空", trigger: "blur" }
     ],
     mainProducts: [
       { required: true, message: "主要农产品不能为空", trigger: "change" }
     ],
     scale: [
       { required: true, message: "种植/养殖规模不能为空", trigger: "blur" }
     ],
     idCardFront: [
       { required: true, message: "身份证正面不能为空", trigger: "change" }
     ],
     idCardBack: [
       { required: true, message: "身份证反面不能为空", trigger: "change" }
     ],
     landProof: [
       { required: true, message: "土地证明/承包合同不能为空", trigger: "change" }
     ],
     productPhotos: [
       { required: true, message: "农产品照片不能为空", trigger: "change" }
     ],
 })
 
 // 表单模板引用
 const baseInfoRef = ref(null)
 const authInfoRef = ref(null)
 const confirmInfoRef = ref(null)

// 验证表单函数
const checkFormValidity = async (formRef) => {
  if (!formRef?.value) return;
  await formRef.value.validate();
  activeStep.value++;
};


// 提交表单函数
const submitForm = async () => {
  loading.value = true;

  // 安全处理数组字段
  const processArrayField = (fieldValue) => {
    if (Array.isArray(fieldValue)) {
      return fieldValue.join(",");
    } else if (fieldValue && typeof fieldValue === 'string') {
      // 如果已经是字符串，直接返回
      return fieldValue;
    } else if (fieldValue) {
      // 如果是其他类型（如对象），尝试转换为字符串
      return String(fieldValue);
    }
    return ""; // 空值返回空字符串
  };

  const submitData = {
    ...form.value,
    mainProducts: processArrayField(form.value.mainProducts),
    otherProof: processArrayField(form.value.otherProof)
  }

  try {
    await addFarmers(submitData);
    ElMessage.success("认证申请成功，将在3个工作日内完成审核");
    setTimeout(() => {
      window.location.reload();
    }, 1500);
  } catch (error) {
    handleSubmitError(error);
  } finally {
    loading.value = false;
  }
}


// 验证失败的错误处理函数
 const handleSubmitError = (error) => {
   if (error.response) {
    const errorMsg = error.response.data?.message || '提交失败，请检查数据';
    ElMessage.error(`提交失败: ${errorMsg}`);
  } else if (error.request) {
    ElMessage.error('网络错误，请检查网络连接');
  } else {
    ElMessage.error(`提交失败: ${error.message}`);
  }
}
 // 统一处理 验证失败/填写不完整 错误
const handleValidationError = (error) => {
  console.error('验证失败:', error);
  
  if (error.errors?.length) {
    const firstError = error.errors[0];
    ElMessage.error(firstError.message || "请填写完整的表单信息");
  } else {
    ElMessage.error(error.message || "请填写完整的表单信息");
  }
};
 // 表单操作按钮
 // 下一步
const handleFormActionsNext = async () => {
  try {
    switch (activeStep.value) {
      case 0:  // 第一步验证
        await checkFormValidity(baseInfoRef)
        break
      case 1: // 第二步验证
        await checkFormValidity(authInfoRef)
        break
      case 2: // 第三步直接提交，不需要验证
        await submitForm();
        break;
    }
  } catch (error) {
    // 验证失败的错误处理
    handleValidationError(error)
  }
};


 // 上一步
 const handleFormActionsPrev = async () => {
   if (activeStep.value != 0)
   activeStep.value--
}

const showText = (activeStep, loading) => {
  let res = ''
  res = activeStep === 2 ? loading ? "提交中...": "提交认证" : "下一步"
  return res
}
 </script>
 
 <style scoped>

 </style>